// mqttService.js
import mqtt from "mqtt/dist/mqtt";
const mqttBroker = "wsss://broker-cn.emqx.io:8083/mqtt"; //mqtt://localhost:1883
const options = {KeepAlive:60,protocolVersion: 4,clean: true};
const client = mqtt.connect(mqttBroker, options);

client.on("connect", () => {
  console.log("Connected to MQTT broker");
});

client.on("error", (err) => {
  console.error("Connection error: ", err);
});

export const mqttService = {
  publish(topic, message) {
    client.publish(topic, message);
  },
  subscribe(topic, callback) {
    client.subscribe(topic, (err) => {
      if (!err) {
        console.log(`Subscribed to ${topic}`);
        client.on("message", (topic, message) => {
          callback(message);
        });
      }
    });
  },
  unsubscribe(topic) {
    client.unsubscribe(topic, (err) => {
      if (!err) {
        console.log(`Unsubscribed from ${topic}`);
      }else{
        console.error(`Error unsubscribing from ${topic}: ${err}`);
      }
    });
  },
  disconnect() {
    client.end();
  },
};
